# -*- coding: utf-8 -*-
# @Author   : MambaCloud
# @Date     : 2022年1月9日02:47:54
# @Software : PyCharm
# @version  ：Python 3.8
# @File     : algorithm_markdown_table.py
import os
import re

# 基础模板头，个人自定义
MARKDOWN_TABLE_TEMPLATE = """
# 文件夹对应专栏
01：PostgreSQL--源码分析  
02：PostgreSQL--体系结构  
03：PostgreSQL--安全机制  
04：PostgreSQL--故障处理  
05：PostgreSQL--集群架构  
06：PostgreSQL--SQL语言  
07：PostgreSQL--逻辑复制  
08：PostgreSQL--事务、并发、锁  
09：PostgreSQL--备份恢复  
10：PostgreSQL--性能优化  
11：PostgreSQL--日常维护  
12：PostgreSQL--扩展语言  
13：PostgreSQL--物理复制  
14：PostgreSQL--监控告警  
15：PostgreSQL--压力测试  
# PostgreSQL
| 编 号  | 分 类 | 内容 |  相应链接 |
| ----- | ----- | ---- |  ------ | 
"""


class MakeAlgorithmMarkdownTable:
    def __init__(self, search_path, excludes):
        self.search_path = search_path
        self.start_dirname = os.path.basename(self.search_path)
        self.excludes = excludes
        self.programs = []

    def dfs_markdown_path(self, path):
        for child in os.listdir(path):
            if child.lower() in self.excludes:
                continue
            start_index = path.find(self.start_dirname)
            markdown_link_dir = path[start_index:].replace('\\', '/')
            if os.path.isfile(os.path.join(path, child)):
                markdown_link_path = '/'.join([markdown_link_dir, child])
                self.get_code_table(path, child, markdown_link_path)
            else:
                self.dfs_markdown_path(os.path.join(path, child))

    def get_code_table(self, file_path, file_name, abs_path):
        algorithm_type = os.path.split(file_path)[-1].strip('_')
        if algorithm_type == 'image':
            return
        if algorithm_type =='01':
            algorithm_type='PostgreSQL--源码分析'
        elif algorithm_type =='02':
            algorithm_type='PostgreSQL--体系结构'
        elif algorithm_type =='03':
            algorithm_type='PostgreSQL--安全机制'
        elif algorithm_type =='04':
            algorithm_type='PostgreSQL--故障处理'
        elif algorithm_type =='05':
            algorithm_type='PostgreSQL--集群架构'
        elif algorithm_type =='06':
            algorithm_type='PostgreSQL--SQL语言'
        elif algorithm_type =='07':
            algorithm_type='PostgreSQL--逻辑复制'
        elif algorithm_type =='08':
            algorithm_type='PostgreSQL--事务、并发、锁'
        elif algorithm_type =='09':
            algorithm_type='PostgreSQL--备份恢复'
        elif algorithm_type =='10':
            algorithm_type='PostgreSQL--性能优化'
        elif algorithm_type =='11':
            algorithm_type='PostgreSQL--日常维护'
        elif algorithm_type =='12':
            algorithm_type='PostgreSQL--扩展语言'
        elif algorithm_type =='13':
            algorithm_type='PostgreSQL--物理复制'
        elif algorithm_type =='14':
            algorithm_type='PostgreSQL--监控告警'
        elif algorithm_type =='15':
            algorithm_type='PostgreSQL--压力测试'
        else:
            algorithm_type='PostgreSQL--其他内容'
        code_file_name = os.path.splitext(file_name)[0]
        git_file_link = f"[点击跳转](https://gitee.com/MambaCloud/cloud/tree/master/{abs_path})"
        level = None
        link = None
        with open(os.path.join(file_path, file_name), 'r', encoding='utf-8') as f:
            for i in range(10):
                info = f.readline().strip().replace("链接：","")
                get_level = re.match('>.*难度[：|:]', info)
                if get_level:
                    # 正则获取解析的span尾节点
                    level = info[get_level.span()[1]:]
                # 获取力扣题目链接
                get_link = re.match('.*https://leetcode-cn.com', info)
                if get_link:
                    link = info[get_link.span()[0]:].strip('> ')
        self.programs.append([algorithm_type,
                              code_file_name,
                              git_file_link])

    @staticmethod
    def sort_title(title):
        title = title.split('.')[0].strip()
        if title.isdigit():
            return int(title)
        return 1000

    def run(self):
        self.dfs_markdown_path(self.search_path)
        self.programs.sort(key=lambda x: self.sort_title(x[1]))
        with open(os.path.join(os.path.dirname(self.search_path), "README.md"),
                  'w', encoding='utf-8') as readme_file:
            readme_file.write(MARKDOWN_TABLE_TEMPLATE)
            for index, info in enumerate(self.programs, start=1):
                readme_file.write("|{}|{}|{}|{}|\n".format(index, *info))


if __name__ == '__main__':
    # 历史算法解题目录
    MARKDOWN_PATH = os.getcwd()
    # 例外文件列表
    EXCLUDE_FILES = ['readme.md','algorithm_markdown_table.py']
    m = MakeAlgorithmMarkdownTable(MARKDOWN_PATH, EXCLUDE_FILES)
    m.run()
